package com.ruoyi.report.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.pojo.WeChat;
import com.ruoyi.report.domain.SectorMsg;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.pojo.WeChat;
import cn.hutool.json.JSONUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@RestController
@RequestMapping("/weChat")
public class WeChatController {

    /**
     * 获取getOpenId
     */
    @GetMapping("/getOpenId")
    public AjaxResult getOpenId( String code) throws Exception
    {
        // 填写你自己的AppID和AppSecret
        String appId = "wx87bd10784fc8639a";
        String appSecret = "6b5540d92c3c6a183985cec801c38b18";
        String jsCode = code;  // 前端传来的jsCode

        // 请求URL，获取access_token和openid
        String urlStr = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId +
                        "&secret=" + appSecret + "&js_code=" + jsCode + "&grant_type=authorization_code";

        // 发起HTTP请求
        String response = sendHttpRequest(urlStr);
        WeChat sessionInfo = JSONUtil.toBean(response, WeChat.class);
        return AjaxResult.success(sessionInfo);
    }
    private  String sendHttpRequest(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }
}
